﻿using System.Linq;
using System.Net.Mail;
using System.Text;
using Castle.Core.Smtp;

namespace Wolfpack.Contrib.Publishers.Email
{
    public abstract class SmtpUtility
    {
        public abstract bool IsHtml { get; }
        public abstract bool GetHtmlView(NotificationModel model, out AlternateView view);
        public abstract bool GetTextView(NotificationModel model, out AlternateView view);

        public EmailConfiguration Configuration { get; private set; }

        protected SmtpUtility(EmailConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void Send(NotificationModel model)
        {
            using (var message = new MailMessage
                                {
                                    IsBodyHtml = IsHtml,
                                    BodyEncoding = Encoding.UTF8,
                                    Subject = CustomiseSubject(model),
                                    SubjectEncoding = Encoding.UTF8
                                })
            {
                message.From = new MailAddress(Configuration.FromAddress, Configuration.FromName, Encoding.UTF8);

                Configuration.ToAddress.Split(';')
                    .Where(addr => !string.IsNullOrWhiteSpace(addr))
                    .Select(addr => addr.Trim())
                    .ToList()
                    .ForEach(addr => message.To.Add(addr));

                AlternateView view;

                if (IsHtml && GetHtmlView(model, out view))
                    message.AlternateViews.Add(view);

                if (GetTextView(model, out view))
                    message.AlternateViews.Add(view);

                var sender = new DefaultSmtpSender(Configuration.SmtpHost)
                {
                    Port = Configuration.Port,
                    Domain = Configuration.Domain,
                    Password = Configuration.Password,
                    UseSsl = Configuration.UseSsl.GetValueOrDefault(false),
                    UserName = Configuration.UserName
                };

                sender.Send(message);
            }
        }

        protected virtual string CustomiseSubject(NotificationModel model)
        {
            return string.Format("{0} - {1} ({2})", Configuration.MailSubject, model.CheckId, model.Info ?? "no info");
        }
    }
}